package api

import (
	"FeedXmh/app/dao"
	"FeedXmh/redis"
	"fmt"
	jwt "github.com/gogf/gf-jwt"
	"github.com/gogf/gf/database/gdb"
	"github.com/gogf/gf/frame/g"
	"github.com/gogf/gf/net/ghttp"
	"github.com/gogf/gf/os/gtime"
	"github.com/gogf/gf/text/gstr"
	"github.com/gogf/gf/util/gconv"
	"github.com/xuri/excelize/v2"
	"paco_toolkit/common"
)

var House = house{}

type house struct{}

func (a *house) GET(r *ghttp.Request) {
	res := g.Map{
		"code":  0,
		"msg":   "",
		"data":  nil,
		"count": 0,
	}
	params := r.GetQueryMap()

	id := gconv.String(params["id"])
	farmid := gconv.String(params["farmid"])
	key := gconv.String(params["key"])

	claims := jwt.ExtractClaims(r)
	userid := claims["userid"].(string)
	url := r.URL.Path

	db := g.DB(g.Cfg().GetString("custom.db_name"))
	if dao.CheckApiPermission(url, r.Method, userid) {
		model := db.Model("v_house")
		if id != "" {
			model.Where(" id=? ", id)
		}
		if farmid != "" {
			model.Where(" farmid=? ", farmid)
		}
		if key != "" {
			model.Where(" housename like '%?%'", key)
		}

		if dao.IsAdmin(userid) || dao.IsService(userid) {

		} else {
		}
		r, err := model.Order(" farmid asc,sort desc,id ASC, housename ASC ").All()
		if err != nil {
			g.Log().Line().Error(err)
			res["code"] = -1
			res["msg"] = err.Error()
		} else {
			list := r.List()
			res["data"] = list
			res["count"] = len(list)
		}
	} else {
		res["code"] = -1
		res["msg"] = "您没有该操作权限"
	}

	r.Response.WriteJson(res)
	r.ExitAll()
}

func (a *house) PUT(r *ghttp.Request) {
	res := g.Map{
		"code":  0,
		"msg":   "",
		"data":  nil,
		"count": 0,
	}
	params := r.GetFormMap()

	claims := jwt.ExtractClaims(r)
	current_user := claims["userid"].(string)
	url := r.URL.Path

	params["update_date"] = gtime.Now().String()
	params["update_user"] = current_user
	id := gconv.String(params["id"])

	if dao.CheckApiPermission(url, r.Method, current_user) {
		db := g.DB(g.Cfg().GetString("custom.db_name"))
		_, err := db.Model("t_house").Data(params).Save()
		if err != nil {
			res["code"] = -1
			res["msg"] = err.Error()
		} else {
			res["code"] = 0
			res["msg"] = "保存成功"
			res["data"] = id

		}
	} else {
		res["code"] = -1
		res["msg"] = "您没有该操作权限"
	}
	r.Response.WriteJson(res)
	r.ExitAll()
}

func (a *house) POST(r *ghttp.Request) {
	res := g.Map{
		"code":  0,
		"msg":   "",
		"data":  nil,
		"count": 0,
	}
	params := r.GetFormMap()

	_, exist := params["id"]
	if exist {
		delete(params, "id")
	}

	claims := jwt.ExtractClaims(r)
	current_user := claims["userid"].(string)
	url := r.URL.Path
	params["create_date"] = gtime.Now().String()
	params["create_user"] = current_user

	if dao.CheckApiPermission(url, r.Method, current_user) {
		db := g.DB(g.Cfg().GetString("custom.db_name"))
		re, err := db.Model("t_house").Data(params).Save()
		if err == nil {
			newid, _ := re.LastInsertId()
			res["code"] = 0
			res["msg"] = "保存成功"
			res["data"] = newid
		} else {
			res["code"] = -1
			res["msg"] = err.Error()
		}
	} else {
		res["code"] = -1
		res["msg"] = "您没有该操作权限"
	}
	r.Response.WriteJson(res)
	r.ExitAll()
}

func (a *house) DELETE(r *ghttp.Request) {
	res := g.Map{
		"code":  0,
		"msg":   "",
		"data":  nil,
		"count": 0,
	}
	params := r.GetFormMap()

	id, exist := params["id"]
	if exist {
		claims := jwt.ExtractClaims(r)
		current_user := claims["userid"].(string)
		url := r.URL.Path
		params["lpt"] = gtime.Now().String()
		params["whom"] = current_user
		//db:=g.DB(g.Cfg().GetString("custom.db_name"))
		if dao.CheckApiPermission(url, r.Method, current_user) {
			_, err := dao.T_house.Delete(gconv.String(id))
			if err != nil {
				g.Log().Line().Error(err)
				res["code"] = -1
				res["msg"] = err.Error()
			}
		} else {
			res["code"] = -1
			res["msg"] = "您没有该操作权限"
		}
	} else {
		res["code"] = -1
		res["msg"] = "错误的参数"
	}

	r.Response.WriteJson(res)
	r.ExitAll()
}

// ListByUser 上级(建立账户者)/管理员 查看下级用户具有的栏舍列表
func (a *house) ListByUser(r *ghttp.Request) {
	res := g.Map{
		"code":  0,
		"msg":   "",
		"data":  nil,
		"count": 0,
	}
	params := r.GetQueryMap()

	userid := gconv.String(params["userid"])
	//key :=gconv.String(params["key"])

	claims := jwt.ExtractClaims(r)
	cur_userid := claims["userid"].(string)
	url := r.URL.Path

	//db:=g.DB(g.Cfg().GetString("custom.db_name"))
	if dao.CheckApiPermission(url, r.Method, cur_userid) {
		house_list := dao.GetPermisHouse(userid)
		res["data"] = house_list
		res["count"] = len(house_list)
	} else {
		res["code"] = -1
		res["msg"] = "您没有该操作权限"
	}

	r.Response.WriteJson(res)
	r.ExitAll()
}

func (a *house) GetUsers(r *ghttp.Request) {
	res := g.Map{
		"code":  0,
		"msg":   "",
		"data":  nil,
		"count": 0,
	}
	params := r.GetQueryMap()

	houseid := gconv.String(params["houseid"])

	claims := jwt.ExtractClaims(r)
	userid := claims["userid"].(string)
	url := r.URL.Path
	db := g.DB(g.Cfg().GetString("custom.db_name"))
	if dao.CheckApiPermission(url, r.Method, userid) {
		r, err := db.GetAll(fmt.Sprintf("SELECT * FROM v_user WHERE userid in (SELECT userid FROM t_user_house WHERE houseid=%s);", houseid))
		if err != nil {
			g.Log().Line().Error(err)
			res["code"] = -1
			res["msg"] = err.Error()
		} else {
			list := r.List()

			res["data"] = list
			res["count"] = len(list)
		}
	} else {
		res["code"] = -1
		res["msg"] = "您没有该操作权限"
	}
	r.Response.WriteJson(res)
	r.ExitAll()
}

func (a *house) SetUsers(r *ghttp.Request) {
	res := g.Map{
		"code":  0,
		"msg":   "",
		"data":  nil,
		"count": 0,
	}
	params := r.GetFormMap()

	claims := jwt.ExtractClaims(r)
	current_user := claims["userid"].(string)
	url := r.URL.Path

	houseid := gconv.String(params["houseid"])
	userids := gconv.String(params["userids"])
	delete(params, "userids")
	if dao.CheckApiPermission(url, r.Method, current_user) {
		db := g.DB(g.Cfg().GetString("custom.db_name"))
		if tx, err := db.Begin(); err == nil {
			_, err = tx.Model("t_user_house").Where("houseid=?", houseid).Delete()
			if err == nil {
				if userids != "" {
					var _list gdb.List
					_userids := gstr.Split(userids, ",")
					for _, userid := range _userids {
						_item := gdb.Map{
							"userid":      userid,
							"houseid":     houseid,
							"create_date": gtime.Now().String(),
							"create_user": current_user,
						}
						_list = append(_list, _item)
					}

					if len(_list) > 0 {
						_, err = tx.Model("t_user_house").Data(_list).Save()
					}
				}
			}

			if err != nil {
				tx.Rollback()
				res["code"] = -1
				res["msg"] = err.Error()
			} else {
				tx.Commit()
				res["code"] = 0
				res["msg"] = "保存成功"
			}
		}
	} else {
		res["code"] = -1
		res["msg"] = "您没有该操作权限"
	}
	r.Response.WriteJson(res)
	r.ExitAll()
}

func (a *house) GetWithDetail(r *ghttp.Request) {
	res := g.Map{
		"code":  0,
		"msg":   "",
		"data":  nil,
		"count": 0,
	}
	params := r.GetQueryMap()

	id := gconv.String(params["id"])
	farmid := gconv.String(params["farmid"])
	key := gconv.String(params["key"])

	claims := jwt.ExtractClaims(r)
	userid := claims["userid"].(string)
	url := r.URL.Path

	db := g.DB(g.Cfg().GetString("custom.db_name"))
	if dao.CheckApiPermission(url, r.Method, userid) {
		model := db.Model("t_house")
		if id != "" {
			model.Where(" id=? ", id)
		}
		if farmid != "" {
			model.Where(" farmid=? ", farmid)
		}
		if key != "" {
			model.Where(" housename like '%?%'", key)
		}

		r, err := model.All()
		if err != nil {
			g.Log().Line().Error(err)
			res["code"] = -1
			res["msg"] = err.Error()
		} else {
			list := r.List()
			for k, v := range list {
				housid := gconv.String(v["id"])

				sql := " SELECT d.houseid,count(s.online=1 or null) as onlineNum,count(1) as deviceNum,COUNT(s.alarm>0 or s.online=0 or null) as alarmNum FROM v_device d " +
					" inner JOIN t_hzfgw_node_status s on d.device_addr = s.addr " +
					fmt.Sprintf(" WHERE d.houseid = %s GROUP BY d.houseid", housid)
				dt, err := db.GetOne(sql)
				if err != nil {
					g.Log().Line().Error(err)
				} else {
					if dt != nil {
						list[k]["onlineNum"] = dt.Map()["onlineNum"]
						list[k]["deviceNum"] = dt.Map()["deviceNum"]
						list[k]["alarmNum"] = dt.Map()["alarmNum"]
					} else {
						list[k]["onlineNum"] = 0
						list[k]["deviceNum"] = 0
						list[k]["alarmNum"] = 0
					}

				}

				today := gtime.Now().Format(common.DATE_FORMAT)
				sql = fmt.Sprintf("SELECT sum(day_use_feed_auto) AS day_use_feed_auto,sum(day_use_feed_man) AS day_use_feed_man,sum(day_use_water_auto) AS day_use_water_auto,sum(day_use_water_man) AS day_use_water_man ,his_date FROM t_hzfgw_node_status_his WHERE addr in ( SELECT device_addr FROM t_device WHERE houseid=%s ) AND his_date='%s' ", housid, today)
				dt, err = db.GetOne(sql)
				if err != nil {
					g.Log().Line().Error(err)
				} else {
					if dt != nil {
						list[k]["TodayFeed"] = dt.Map()
					}

				}
			}
			res["data"] = list
			res["count"] = len(list)
		}
	} else {
		res["code"] = -1
		res["msg"] = "您没有该操作权限"
	}

	r.Response.WriteJson(res)
	r.ExitAll()
}

func (a *house) SummaryInfo(r *ghttp.Request) {
	res := g.Map{
		"code":  0,
		"msg":   "",
		"data":  nil,
		"count": 0,
	}
	params := r.GetQueryMap()
	id := gconv.String(params["id"])
	farmid := gconv.String(params["farmid"])
	house_type := gconv.String(params["house_type"])
	claims := jwt.ExtractClaims(r)
	userid := claims["userid"].(string)
	url := r.URL.Path
	db := g.DB(g.Cfg().GetString("custom.db_name"))
	if dao.CheckApiPermission(url, r.Method, userid) {
		model := db.Model("t_house")
		if id != "" {
			model.Where(" id=? ", id)
		}
		if farmid != "" {
			model.Where(" farmid=? ", farmid)
		}
		if house_type != "" {
			model.Where(" type=? ", house_type)
		}
		r, err := model.All()
		if err != nil {
			g.Log().Line().Error(err)
			res["code"] = -1
			res["msg"] = err.Error()
		} else {
			var newList g.List
			list := r.List()
			for _, v := range list {
				housid := gconv.String(v["id"])
				json_str := redis.GetHouseSummary(housid)
				if json_str != "" {
					item := gconv.Map(json_str)
					newList = append(newList, item)
				}
				/*farmid := gconv.String(v["farmid"])
								housename := gconv.String(v["housename"])
								house_type := gconv.String(v["type"])

								sql := fmt.Sprintf(`SELECT houseid,farmid,housename,house_type,
				sum(if(mode>0,pig_num,0)) as pig_num_total,
				sum(if(mode>0,son,0)) as son_total,
				sum(if(mode=0,1,0)) as num_stop,
				sum(if(mode>0,pig_num,0)) as pig_num,
				sum(if(online=1,1,0)) as online_num,
				sum(if(online=0 || online is NULL,1,0)) as offline_num,
				sum(if(alarm>0||alarm_ext>0|| online=0 || online is NULL,1,0)) as alarm_device_num,
				sum(if(online=1,max_feed,0)) as max_feed,
				sum(if(online=1,day_use_feed_auto,0)) as day_use_feed_auto,
				sum(if(online=1,day_use_feed_man,0)) as day_use_feed_man,
				sum(if(online=1,day_use_water_auto,0)) as day_use_water_auto,
				sum(if(online=1,day_use_water_man,0)) as day_use_water_man,
				sum(if(online=1,day_use_feed_auto+day_use_feed_man,0) ) as today_feed,
				sum(if(online=1,day_use_water_auto+day_use_water_man,0)) as today_water
				FROM v_hzgw_node WHERE houseid='%s';`, housid)
								dt, err := db.GetOne(sql)
								if err != nil {
									res["code"] = -1
									res["msg"] = err.Error()
								} else {
									list[k] = dt.Map()
									list[k]["housid"] = housid
									list[k]["farmid"] = farmid
									list[k]["housename"] = housename
									list[k]["house_type"] = house_type

									//昨日下料，昨日下水
									yestoday := gtime.Now().AddDate(0, 0, -1).Format(common.DATE_FORMAT)
									sql = fmt.Sprintf(`SELECT sum(day_use_feed_auto+day_use_feed_man) AS feed
						,SUM(day_use_water_auto+day_use_water_man) as water
						FROM t_hzfgw_node_status_his
						WHERE addr in (SELECT device_addr FROM v_device WHERE houseid='%s') and his_date='%s';`, housid, yestoday)

									dt1, err := db.GetOne(sql)
									if err != nil {
										g.Log().Line().Error(err)
									} else {
										data1 := dt1.Map()
										list[k]["yestoday_feed"] = data1["feed"]
										list[k]["yestoday_water"] = data1["water"]
									}

								}

				*/

			}
			res["data"] = newList
		}

	} else {
		res["code"] = -1
		res["msg"] = "您没有该操作权限"
	}
	r.Response.WriteJson(res)
	r.ExitAll()
}

func (a *house) DeviceData(r *ghttp.Request) {
	res := g.Map{
		"code":  0,
		"msg":   "",
		"data":  nil,
		"count": 0,
	}
	params := r.GetQueryMap()
	id := gconv.String(params["id"])

	claims := jwt.ExtractClaims(r)
	userid := claims["userid"].(string)
	url := r.URL.Path
	db := g.DB(g.Cfg().GetString("custom.db_name"))
	if dao.CheckApiPermission(url, r.Method, userid) {
		data := g.Map{}

		sql := " SELECT d.houseid,d.device_addr,d.alive as online,count(s.online=1 or null) as onlineNum,count(1) as deviceNum,COUNT(s.alarm>0 or null) as alarmNum FROM v_device d " +
			" LEFT JOIN t_hzfgw_node_status s on d.device_addr = s.addr " +
			fmt.Sprintf(" WHERE d.houseid = %s GROUP BY d.houseid,d.device_addr,d.alive", id)
		dtList, err := db.GetAll(sql)
		if err != nil {
			res["code"] = -1
			res["msg"] = err.Error()
		} else {
			all_onlineNum := 0
			all_deviceNum := 0
			all_alarmNum := 0
			if dtList.Len() > 0 {
				for _, dt := range dtList {
					online := gconv.Int(dt["online"])
					onlineNum := gconv.Int(dt["onlineNum"])
					deviceNum := gconv.Int(dt["deviceNum"])
					alarmNum := gconv.Int(dt["alarmNum"])
					if online > 0 {
						all_onlineNum += onlineNum
					}
					all_deviceNum += deviceNum
					all_alarmNum += alarmNum
				}
			}
			data["onlineNum"] = all_onlineNum
			data["deviceNum"] = all_deviceNum
			data["alarmNum"] = all_alarmNum
		}

		//统计猪
		son := 0
		sql = fmt.Sprintf("SELECT sum(son) as son FROM t_hzfgw_node_para WHERE addr in (SELECT device_addr FROM v_device WHERE houseid=%s) AND `mode` in (1,2,6);", id)
		dt, err := db.GetOne(sql)
		if err != nil {
			res["code"] = -1
			res["msg"] = err.Error()
		} else {
			son += gconv.Int(dt.Map()["son"])
		}
		sql = fmt.Sprintf("SELECT sum(son+1) as son FROM t_hzfgw_node_para WHERE addr in (SELECT device_addr FROM v_device WHERE houseid=%s) AND `mode` in (5);", id)
		dt, err = db.GetOne(sql)
		if err != nil {
			res["code"] = -1
			res["msg"] = err.Error()
		} else {
			son += gconv.Int(dt.Map()["son"])
		}
		data["pigNum"] = son

		res["data"] = data
		res["count"] = 1
	} else {
		res["code"] = -1
		res["msg"] = "您没有该操作权限"
	}
	r.Response.WriteJson(res)
	r.ExitAll()
}

func (a *house) TodayFeed(r *ghttp.Request) {
	res := g.Map{
		"code":  0,
		"msg":   "",
		"data":  nil,
		"count": 0,
	}
	params := r.GetQueryMap()
	id := gconv.String(params["id"])

	claims := jwt.ExtractClaims(r)
	userid := claims["userid"].(string)
	url := r.URL.Path
	db := g.DB(g.Cfg().GetString("custom.db_name"))
	if dao.CheckApiPermission(url, r.Method, userid) {
		data := g.Map{}
		today := gtime.Now().Format(common.DATE_FORMAT)
		sql := fmt.Sprintf("SELECT sum(day_use_feed_auto) AS day_use_feed_auto,sum(day_use_feed_man) AS day_use_feed_man,sum(day_use_water_auto) AS day_use_water_auto,sum(day_use_water_man) AS day_use_water_man ,his_date FROM t_hzfgw_node_status_his WHERE addr in ( SELECT device_addr FROM t_device WHERE houseid=%s ) AND his_date='%s' ", id, today)
		dt, err := db.GetOne(sql)
		if err != nil {
			res["code"] = -1
			res["msg"] = err.Error()
		} else {
			data = dt.Map()
			res["data"] = data
			res["count"] = 1
		}
	} else {
		res["code"] = -1
		res["msg"] = "您没有该操作权限"
	}
	r.Response.WriteJson(res)
	r.ExitAll()
}

func (a *house) DayFeed(r *ghttp.Request) {
	res := g.Map{
		"code":  0,
		"msg":   "",
		"data":  nil,
		"count": 0,
	}
	params := r.GetQueryMap()
	id := gconv.String(params["id"])
	begin := gconv.String(params["begin"])
	end := gconv.String(params["end"])
	where := ""

	if begin != "" {
		where += fmt.Sprintf(" and his_date>='%s'", begin)
	}
	if end != "" {
		where += fmt.Sprintf(" and his_date<='%s'", end)
	}

	claims := jwt.ExtractClaims(r)
	userid := claims["userid"].(string)
	url := r.URL.Path
	db := g.DB(g.Cfg().GetString("custom.db_name"))
	if dao.CheckApiPermission(url, r.Method, userid) {

		sql := " SELECT sum(max_feed) AS max_feed,sum(day_use_feed_auto) AS day_use_feed_auto," +
			"sum(day_use_feed_man) AS day_use_feed_man,sum(day_use_water_auto) AS day_use_water_auto," +
			"sum(day_use_water_man) AS day_use_water_man ,sum(pig_num) as pig_num,avg(avg_feed) as avg_feed,avg(low_standard) as low_standard,avg(standard) as standard,avg(high_standard) as high_standard,avg(day) as day,his_date " +
			fmt.Sprintf(" FROM t_hzfgw_node_status_his WHERE addr in ( SELECT device_addr FROM t_device WHERE houseid=%s ) and mode!=0", id) + where +
			" GROUP BY his_date ORDER BY his_date asc;"
		dt, err := db.GetAll(sql)
		if err != nil {
			res["code"] = -1
			res["msg"] = err.Error()
		} else {
			res["data"] = dt.List()
			res["count"] = dt.Len()
		}
	} else {
		res["code"] = -1
		res["msg"] = "您没有该操作权限"
	}
	r.Response.WriteJson(res)
	r.ExitAll()
}

func (a *house) ExportDayFeed(r *ghttp.Request) {
	res := g.Map{
		"code":  0,
		"msg":   "",
		"data":  nil,
		"count": 0,
	}
	params := r.GetQueryMap()
	id := gconv.String(params["id"])
	begin := gconv.String(params["begin"])
	end := gconv.String(params["end"])
	where := fmt.Sprintf(" his.mode!=0 and v.houseid=%s", id)
	if begin != "" {
		where += fmt.Sprintf(" and his.his_date>='%s'", begin)
	}
	if end != "" {
		where += fmt.Sprintf(" and his.his_date<='%s'", end)
	}

	claims := jwt.ExtractClaims(r)
	userid := claims["userid"].(string)
	url := r.URL.Path
	db := g.DB(g.Cfg().GetString("custom.db_name"))
	if dao.CheckApiPermission(url, r.Method, userid) {
		sql := " SELECT v.farmname,v.housename,sum(his.max_feed) AS max_feed,sum(his.day_use_feed_auto) AS day_use_feed_auto," +
			"sum(his.day_use_feed_man) AS day_use_feed_man,sum(his.day_use_water_auto) AS day_use_water_auto," +
			"sum(his.day_use_water_man) AS day_use_water_man ,sum(his.pig_num) as pig_num,avg(his.avg_feed) as avg_feed,sum(his.day_use_feed_auto+his.day_use_feed_man) AS feed,sum(his.day_use_water_auto+his.day_use_water_man) as water,avg(his.low_standard) as low_standard,avg(his.standard) as standard,avg(his.high_standard) as high_standard,avg(his.day) as day,his.his_date " +
			" FROM t_hzfgw_node_status_his his left join v_device v on v.device_addr=his.addr WHERE " + where +
			" GROUP BY his.his_date ORDER BY his.his_date asc;"
		dt, err := db.GetAll(sql)
		if err != nil {
			g.Log().Line().Error(err)
			res["code"] = -1
			res["msg"] = err.Error()
			r.Response.WriteJson(res)
		} else {
			//数据正常导出

			f := excelize.NewFile()
			defer func() {
				if err := f.Close(); err != nil {
					g.Log().Line(true).Error(err)
				}
			}()

			// 创建一个工作表
			index, err := f.NewSheet("Sheet1")
			if err != nil {
				g.Log().Line(true).Error(err)
			}

			//样式
			style_header, _ := f.NewStyle(&excelize.Style{
				Fill:      excelize.Fill{Type: "pattern", Color: []string{"#4958b9"}, Pattern: 1},
				Font:      &excelize.Font{Color: "#ffffff", Bold: true},
				Alignment: &excelize.Alignment{Vertical: "center", Horizontal: "center"},
			})
			style_yellow_font, _ := f.NewStyle(&excelize.Style{
				Font: &excelize.Font{Color: "#FF8010"},
			})
			style_yellow_light_font, _ := f.NewStyle(&excelize.Style{
				Font: &excelize.Font{Color: "#FFB800"},
			})
			style_green_font, _ := f.NewStyle(&excelize.Style{
				Font: &excelize.Font{Color: "#05982E"},
			})

			//列宽
			f.SetColWidth("Sheet1", "A", "J", 20)

			// 标题
			f.SetCellValue("Sheet1", "A1", "场区")
			f.SetCellValue("Sheet1", "B1", "单元")
			f.SetCellValue("Sheet1", "C1", "日龄")
			f.SetCellValue("Sheet1", "D1", "采食日期")
			f.SetCellValue("Sheet1", "E1", "存栏")
			f.SetCellValue("Sheet1", "F1", "总采食(kg)")
			f.SetCellValue("Sheet1", "G1", "头均采食(kg)")
			f.SetCellValue("Sheet1", "H1", "采食状况")
			f.SetCellValue("Sheet1", "I1", "头均低区间(kg)")
			f.SetCellValue("Sheet1", "J1", "头均正常区间(kg)")
			f.SetCellValue("Sheet1", "K1", "头均高区间(kg)")
			f.SetCellValue("Sheet1", "L1", "饮水量(L)")

			f.SetCellStyle("Sheet1", "A1", "A1", style_header)
			f.SetCellStyle("Sheet1", "B1", "B1", style_header)
			f.SetCellStyle("Sheet1", "C1", "C1", style_header)
			f.SetCellStyle("Sheet1", "D1", "D1", style_header)
			f.SetCellStyle("Sheet1", "E1", "E1", style_header)
			f.SetCellStyle("Sheet1", "F1", "F1", style_header)
			f.SetCellStyle("Sheet1", "G1", "G1", style_header)
			f.SetCellStyle("Sheet1", "H1", "H1", style_header)
			f.SetCellStyle("Sheet1", "I1", "I1", style_header)
			f.SetCellStyle("Sheet1", "J1", "J1", style_header)
			f.SetCellStyle("Sheet1", "K1", "K1", style_header)
			f.SetCellStyle("Sheet1", "L1", "L1", style_header)

			list := dt.List()
			if len(list) > 0 {
				count := 0
				for k, v := range list {
					count++
					//行数限制
					if count > 1048000 {
						break
					}

					f.SetCellValue("Sheet1", fmt.Sprintf("A%d", k+2), gconv.String(v["farmname"]))
					f.SetCellValue("Sheet1", fmt.Sprintf("B%d", k+2), gconv.String(v["housename"]))
					f.SetCellValue("Sheet1", fmt.Sprintf("C%d", k+2), fmt.Sprintf("%d", gconv.Int(v["day"])))
					f.SetCellValue("Sheet1", fmt.Sprintf("D%d", k+2), gconv.String(v["his_date"]))
					f.SetCellValue("Sheet1", fmt.Sprintf("E%d", k+2), gconv.String(v["pig_num"]))
					f.SetCellValue("Sheet1", fmt.Sprintf("F%d", k+2), fmt.Sprintf("%.3f", gconv.Float32(v["feed"])))
					f.SetCellValue("Sheet1", fmt.Sprintf("G%d", k+2), fmt.Sprintf("%.3f", gconv.Float32(v["avg_feed"])))
					var low_standard, high_standard, avg_feed float32
					low_standard = gconv.Float32(v["low_standard"])
					high_standard = gconv.Float32(v["high_standard"])
					avg_feed = gconv.Float32(v["avg_feed"])
					var health, feed_str string
					if low_standard <= avg_feed && avg_feed <= high_standard {
						//正常采食
						health = "good"
					} else {
						if low_standard > avg_feed {
							//低采食
							health = "low"
						} else if high_standard < avg_feed {
							//高采食
							health = "high"
						}
					}
					if health == "low" {
						f.SetCellStyle("Sheet1", fmt.Sprintf("H%d", k+2), fmt.Sprintf("H%d", k+2), style_yellow_font)
						feed_str = "↓采食量低"
					} else if health == "good" {
						f.SetCellStyle("Sheet1", fmt.Sprintf("H%d", k+2), fmt.Sprintf("H%d", k+2), style_green_font)
						feed_str = "采食量达标"
					} else if health == "high" {
						f.SetCellStyle("Sheet1", fmt.Sprintf("H%d", k+2), fmt.Sprintf("H%d", k+2), style_yellow_light_font)
						feed_str = "↑采食量高"
					}
					f.SetCellValue("Sheet1", fmt.Sprintf("H%d", k+2), feed_str)

					f.SetCellValue("Sheet1", fmt.Sprintf("I%d", k+2), fmt.Sprintf("%.3f", low_standard))
					f.SetCellValue("Sheet1", fmt.Sprintf("J%d", k+2), fmt.Sprintf("%.3f", low_standard)+" - "+fmt.Sprintf("%.3f", high_standard))
					f.SetCellValue("Sheet1", fmt.Sprintf("K%d", k+2), fmt.Sprintf("%.3f", high_standard))

					f.SetCellValue("Sheet1", fmt.Sprintf("L%d", k+2), fmt.Sprintf("%.3f", gconv.Float32(v["water"])))
				}
			}

			// 设置工作簿的默认工作表
			f.SetActiveSheet(index)
			f.Write(r.Response.Writer)
		}
	} else {
		res["code"] = -1
		res["msg"] = "您没有该操作权限"
		r.Response.WriteJson(res)
	}
	r.ExitAll()
}

/*func (a *house) DayAvgFeed(r *ghttp.Request) {
	res := g.Map{
		"code":  0,
		"msg":   "",
		"data":  nil,
		"count": 0,
	}
	params := r.GetQueryMap()
	id := gconv.String(params["id"])
	begin := gconv.String(params["begin"])
	end := gconv.String(params["end"])
	where := ""

	if begin != "" {
		where += fmt.Sprintf(" and his_date>='%s'", begin)
	}
	if end != "" {
		where += fmt.Sprintf(" and his_date<='%s'", end)
	}

	claims := jwt.ExtractClaims(r)
	userid := claims["userid"].(string)
	url := r.URL.Path
	db := g.DB(g.Cfg().GetString("custom.db_name"))
	if dao.CheckApiPermission(url, r.Method, userid) {

		sql := " SELECT avg(day_use_feed_auto) AS day_use_feed_auto,avg(day_use_feed_man) AS day_use_feed_man,avg(day_use_water_auto) AS day_use_water_auto,avg(day_use_water_man) AS day_use_water_man ,sum(pig_num) as pig_num,his_date " +
			fmt.Sprintf(" FROM t_hzfgw_node_status_his WHERE addr in ( SELECT device_addr FROM t_device WHERE houseid=%s ) and mode!=0 ", id) + where +
			" GROUP BY his_date ORDER BY his_date asc;"
		dt, err := db.GetAll(sql)
		if err != nil {
			res["code"] = -1
			res["msg"] = err.Error()
		} else {
			res["data"] = dt.List()
			res["count"] = dt.Len()
		}
	} else {
		res["code"] = -1
		res["msg"] = "您没有该操作权限"
	}
	r.Response.WriteJson(res)
	r.ExitAll()
}*/
